//
//  DTBizNavigationAction.m
//  PersonalManager
//
//  Created by hsd on 16/8/10.
//  Copyright © 2016年 Haiyun.Qian. All rights reserved.
//

#import "DTBizNavigationAction.h"
#import "DTWebViewController.h"

@interface DTWebViewController()<UIPopoverPresentationControllerDelegate>

@end


@interface DTBizNavigationAction ()

/** 标题视图,我用UIButton来代替UILabel */
@property(strong,nonatomic) UIButton *titleBtn;

/** 记录弹出来的小视图 */
@property(strong,nonatomic) UIViewController *cusVC;

@end



@implementation DTBizNavigationAction

/** 懒加载titleBtn */
- (UIButton *)titleBtn {
    
    if (!_titleBtn) {
        _titleBtn = [[UIButton alloc] initWithFrame:CGRectMake( 122.5, 14, 130, 30)];
        _titleBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18];
        _titleBtn.titleLabel.contentMode = UIViewContentModeLeft;
        _titleBtn.userInteractionEnabled = NO;
        _titleBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        self.command.controller.navigationItem.titleView = _titleBtn;
    }
    return _titleBtn;
}

/** 自定义配合 DTJavascriptCommand 初始化方法 */
- (instancetype)initWithCommand:(DTJavascriptCommand *)command{
    self = [super init];
    self.command = command;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(emptyTitleView) name:@"viewWillDisAppear" object:nil];
    return self;
}

- (void)setTitle{
    NSString *title = self.command.params[@"title"];
    [self.titleBtn setTitle:title forState:UIControlStateNormal];
    [self mySuccessCallBack];
}

- (void)setIcon{
    [self.titleBtn setTitle:@"公告" forState:UIControlStateNormal];
    BOOL showIcon = self.command.params[@"showIcon"];
    if (showIcon) {
        NSString *iconIndexStr = self.command.params[@"iconIndex"];
        NSInteger iconIndex = [iconIndexStr integerValue];
        NSString *titleStr = [NSString stringWithFormat:@"title%ld",iconIndex - 1];
        [self.titleBtn setImage:[UIImage imageNamed:titleStr] forState:UIControlStateNormal];
        if (self.titleBtn.titleLabel.text) {
            [self.titleBtn setImageEdgeInsets:UIEdgeInsetsMake(0, self.titleBtn.frame.size.width - 60, 0, 0)];
            [self.titleBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 40)];
            
        }
    }
    
}

- (void)setLeft{
    NSString *show = self.command.params[@"show"];
    NSString *control = self.command.params[@"control"];
    NSString *showIcon = self.command.params[@"showIcon"];
    NSString *text = self.command.params[@"text"];
    if ([show integerValue]) {
        UIButton *customLeftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 4, 60, 40)];
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 40, 40)];
        textLabel.text = [text isEqualToString:@""] ? @"返回" : text;
        textLabel.textColor = [UIColor whiteColor];
        textLabel.font = [UIFont boldSystemFontOfSize:18];
        [customLeftBtn addSubview:textLabel];
        if ([showIcon integerValue]) {
            UIImageView *imaView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
            imaView.contentMode = UIViewContentModeScaleAspectFit;
            imaView.image = [UIImage imageNamed:@"icon_previous"];
            [customLeftBtn addSubview:imaView];
        }
        if ([control integerValue]) {
            [customLeftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        }
        UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:customLeftBtn];
        self.command.controller.navigationItem.leftBarButtonItem = customItem;
    }
}

- (void)close{
    [self.command.webView removeFromSuperview];
}

- (void)setRight {
    NSString *show = self.command.params[@"show"];
    NSString *control = self.command.params[@"control"];
    NSString *text = self.command.params[@"text"];
    if ([show integerValue]) {
        UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 60, 4, 60, 40)];
        [rightBtn setTitle:[text isEqualToString:@""] ? @"默认" : text forState:UIControlStateNormal];
        if ([control integerValue]) {
            [rightBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
        }
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        self.command.controller.navigationItem.rightBarButtonItem = rightItem;
    }
}

//当icon不大于2个时,全部显示,当大于2个时,会首先显示第一个和更多两个icon,剩下的等点击更多之后再向下显示所有的
- (void)setMenu{
    NSArray *itemsArray = self.command.params[@"items"];
    NSMutableArray *mutableItems = [NSMutableArray array];
    //要显示的item 3个以下,不用自定义视图
    if (itemsArray.count < 3) {
        for (NSInteger i = itemsArray.count - 1; i >= 0; i --) {
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - (3 - i) * 60, 300, 40, 40)];
            [btn setImage:[UIImage imageNamed:(itemsArray[i])[@"iconId"]] forState:UIControlStateNormal];
            btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
            btn.tag = [(itemsArray[i])[@"id"] integerValue];
            [btn addTarget:self action:@selector(clickMenu:) forControlEvents:UIControlEventTouchUpInside];
            
            UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
            [mutableItems addObject:barItem];
        }
        
        self.command.controller.navigationItem.rightBarButtonItems = mutableItems;
    }
    else {
        //自定义下拉视图,用于显示多个item
        [self showMoreItem];
    }
}

- (void)showMoreItem {
    NSArray *itemsArr = self.command.params[@"items"];
    NSMutableArray *mutableItems = [NSMutableArray array];
    //先创建第一个和显示更多的item
    for (NSInteger i = 0; i < 2; i ++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - (i + 1) * 60, 4, 40, 40)];
        [btn setImage:[UIImage imageNamed: (i == 1) ? (itemsArr[0])[@"iconId"] : @"more"] forState:UIControlStateNormal];
        btn.tag = (i == 1) ? [(itemsArr[0])[@"id"] integerValue] : (itemsArr.count + 1);
        [btn addTarget:self action:@selector(clickMenu:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
        [mutableItems addObject:barItem];
        
    }
    self.command.controller.navigationItem.rightBarButtonItems = mutableItems;
    
}

//点击具体icon时响应方法
- (void)clickMenu:(UIButton *)item {
    switch (item.tag) {
        case 1:
            NSLog(@"========  tag = 1  ========");
            break;
        case 2:
            NSLog(@"========  tag = 2  ========");
            [self.cusVC dismissViewControllerAnimated:YES completion:nil];
            break;
        case 3:
            NSLog(@"========  tag = 3  ========");
            [self.cusVC dismissViewControllerAnimated:YES completion:nil];
            break;
        case 4:
            NSLog(@"========  tag = 4  ========");
            [self.cusVC dismissViewControllerAnimated:YES completion:nil];
            break;
            
        default:
            [self showModalView:item];
            break;
    }
}

//点击更多icon时,弹出的小视图
- (void)showModalView:(UIButton *)item {
    //记录js颜色值
    //NSString *bgColor = self.command.params[@"backgroundColor"];
    
    UIViewController *modalVC = [UIViewController new];
    self.cusVC = modalVC;
    //modalVC.popoverPresentationController.delegate 如果在此处设置,不起作用,因为popoverPresentationController为null
    modalVC.modalPresentationStyle = UIModalPresentationPopover;//弹出模式
    modalVC.view.backgroundColor = [UIColor lightGrayColor];
    modalVC.preferredContentSize = CGSizeMake(120, 124);//设置尺寸
    modalVC.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;//设置箭头方向
    modalVC.popoverPresentationController.sourceRect = item.bounds;//设置箭头所指的位置
    modalVC.popoverPresentationController.sourceView = item;//设置箭头基于哪个控件的显示
    //modalVC.popoverPresentationController.delegate = (DTBrowserViewController *)self.command.controller;
    
    NSArray *itemsArr = self.command.params[@"items"];
    for (int i = 1; i < itemsArr.count; i ++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, (i-1)*42, 120, 40)];
        [btn setBackgroundColor:[UIColor colorWithRed:0.4568 green:0.7606 blue:1.0 alpha:1.0]];
        UIImageView *imaView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        imaView.image = [UIImage imageNamed:(itemsArr[i])[@"iconId"]];
        imaView.contentMode = UIViewContentModeScaleAspectFit;
        [btn addSubview:imaView];
        [btn setTitle:(itemsArr[i])[@"text"] forState:UIControlStateNormal];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 40, 0, 0)];
        btn.tag = [(itemsArr[i])[@"id"] integerValue];
        [btn addTarget:self action:@selector(clickMenu:) forControlEvents:UIControlEventTouchUpInside];
        [modalVC.view addSubview:btn];
    }
    
    [self.command.controller presentViewController:modalVC animated:YES completion:nil];
    
}


- (void)call{
    
    //取出self.command.params[@"users"],self.command.params[@"corpId"],这里未做判断
    
    NSString * str = [[NSString alloc] initWithFormat:@"tel:%@",@"18969063471"];
    UIWebView *callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.command.controller.view addSubview:callWebview];
     
}


- (void)goBack {
    [self.command.controller.navigationController popViewControllerAnimated:YES];
}

- (void)sendMessage {
    NSLog(@"📩📩📩📩📩📩📩📩📩");
}

//清空标题视图,用于设置了标题视图后,界面跳转时,标题的冲突
- (void)emptyTitleView {
    [self.titleBtn removeFromSuperview];
}

- (void)mySuccessCallBack {
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"设置成功", @"success", nil];
    [self.command successRessponse:dic];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
